package ltd.newbee.mall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import ltd.newbee.mall.api.mall.vo.AccessToken;
import ltd.newbee.mall.service.AccessTokenService;
import nuonuo.open.sdk.NNOpenSDK;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(rollbackFor = RuntimeException.class)
public class AccessTokenServiceImpl implements AccessTokenService {

    @Value("${bill.appKey}")
    public String appKey;
    @Value("${bill.appSecret}")
    public String appSecret;
    protected static final Logger logger = LoggerFactory.getLogger(AccessTokenServiceImpl.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public String getMaxAccessToken(NNOpenSDK sdk) {
        logger.info("测试开始获取token========");

        // Redis key
        String redisKey = "max_access_token:" + appKey;

        // 1. 先从 Redis 获取
        String token = (String) redisTemplate.opsForValue().get(redisKey);
        if (token != null && !token.isEmpty()) {
            logger.info("从Redis中获取token=" + token);
            return token;
        }

        // 2. Redis 中没有，从第三方获取新 token
        logger.info("从第三方获取新token");
        String json = sdk.getMerchantToken(appKey, appSecret);
        logger.info("从第三方获取新json=" + json);
        AccessToken accessToken = JSON.parseObject(json, new TypeReference<AccessToken>() {
        });
        String newToken = accessToken.getAccessToken();

        // 3. 存储到 Redis，设置24小时过期
        // 使用24小时过期，确保每天刷新
        redisTemplate.opsForValue().set(redisKey, newToken, 24, TimeUnit.HOURS);

        logger.info("新token已存储到Redis，token=" + newToken);
        return newToken;
    }


}
